package com.zmj.dubboannotation.orderservice.sercive.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zmj.commoncore.dto.CartDTO;
import com.zmj.commoncore.dto.OrderDTO;
import com.zmj.commoncore.utils.DecimalUtil;
import com.zmj.commoncore.utils.SortUtil;
import com.zmj.dubboannotation.orderservice.mapper.MallOrderMapper;
import com.zmj.dubboannotation.orderservice.mapper.OrderChildMapper;
import com.zmj.dubboannotation.orderservice.mapper.OrderItemMapper;
import com.zmj.dubboannotation.orderservice.redis.RedisUtil;
import com.zmj.dubboannotation.serviceapi.api.*;
import com.zmj.dubboannotation.serviceapi.enums.MallEnum;
import com.zmj.dubboannotation.serviceapi.enums.OrderEnum;
import com.zmj.dubboannotation.serviceapi.enums.ProductEnum;
import com.zmj.dubboannotation.serviceapi.enums.ResultEnum;
import com.zmj.dubboannotation.serviceapi.exception.OrderException;
import com.zmj.dubboannotation.serviceapi.model.*;
import com.zmj.dubboannotation.serviceapi.utils.OrderItemUtil;
import com.zmj.dubboannotation.serviceapi.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by: meijun
 * Date: 2018/09/14 22:54
 */
@Service(interfaceClass = OrderService.class)
@Component
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private MallOrderMapper mallOrderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderChildMapper orderChildMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Reference
    private ProductService productService;

    @Reference
    private ShopActivityService shopActivityService;

    @Reference
    private MallActivityService mallActivityService;

    @Reference
    private MemberCouponService memberCouponService;

    @Reference
    private MemberAddressService memberAddressService;

    @Reference
    private FreightConfigService freightConfigService;

    @Reference
    private CartService cartService;


    private static final Integer scale = 10;
    @Override
    public List<MallOrder> findAll() {
        return null;
    }

    @Override
    public List<MallOrder> findByQuery(MallOrder mallOrder) {
        return mallOrderMapper.findByQuery(mallOrder);
    }

    @Override
    @Transactional
    public int createOrder(Map<Object, Object> cart, OrderDTO orderDTO) {
        //获取购物车列表
        Set<Object> keySet = cart.keySet();
        Iterator<Object> iterator = keySet.iterator();

        //订单主表
        MallOrder mallOrder = new MallOrder();

        String areaCode = "";
        //收货地址
        if(null != orderDTO.getAddressId()) {
            MemberAddress address = memberAddressService.findByIdAndMemberId(orderDTO.getAddressId(),orderDTO.getMemberId());
            areaCode = address.getReceiverAddressCode();
            BeanUtils.copyProperties(address,mallOrder);
        }

        mallOrder.setId(IdWorker.getIdStr());
        mallOrder.setOrderSn(IdWorker.getIdStr());

        //该订单总支付金额
        BigDecimal totalPrice = BigDecimal.ZERO;
        //该订单商品总金额
        BigDecimal productTotalPrice = BigDecimal.ZERO;
        //该订单店铺减免总金额
        BigDecimal orderShopDeratePrice = BigDecimal.ZERO;
        //该订单商城减免金额
        BigDecimal orderMallDeratePrice = BigDecimal.ZERO;
        //该订单运费总额等于所有店铺运费相加
        BigDecimal orderPostagePrice = BigDecimal.ZERO;
        //用户获得总积分
        BigDecimal integral = BigDecimal.ZERO;

        while (iterator.hasNext()) {
            //店铺ID
            Object key = iterator.next();

            //店铺下的所有商品
            Object o = cart.get(key);
            JSONObject jsonObject = JSONObject.parseObject(o.toString());

            //订单副表(各个店铺的订单)
            OrderChild orderChild = new OrderChild();
            orderChild.setId(IdWorker.getIdStr());
            orderChild.setMallOrderSn(mallOrder.getOrderSn());
            orderChild.setMemberId(orderDTO.getMemberId());

            Set<String> set = jsonObject.keySet();
            Iterator<String> iterator1 = set.iterator();

            //该店铺商品总额
            BigDecimal shopProductPrice = BigDecimal.ZERO;
            //该店铺订单总额
            BigDecimal shopTotalPrice = BigDecimal.ZERO;
            //该店铺优惠总额
            BigDecimal shopDeratePrice = BigDecimal.ZERO;

            ArrayList<OrderItem> orderItemList = new ArrayList<>();
            while (iterator1.hasNext()) {
                String productKey = iterator1.next();
                //对应不同商品
                JSONObject object = jsonObject.getJSONObject(productKey);
                CartDTO cartDTO = JSONObject.toJavaObject(object, CartDTO.class);

                //获取选中商品
                if(cartDTO.getChecked().intValue() == ProductEnum.CHECKED.getCode()) {

                    //订单详情表
                    OrderItem orderItem = new OrderItem();

                    ProductVO productVO = productService.findProductBySkuId(cartDTO.getProductId());

                    if(null == productVO) {
                        throw new OrderException(ResultEnum.PRODUCT_NOT_EXIST);
                    }
                    if(productVO.getIsGrund().intValue() != ProductEnum.IS_GRUND_UP.getCode() ||
                            productVO.getIsAudit().intValue() != ProductEnum.IS_AUDIT_YES.getCode() ) {
                        throw new OrderException(ResultEnum.PRODUCT_NOT_GRUND);
                    }
                    if(productVO.getProductStock() <= 0 ) {
                        throw new OrderException(ResultEnum.PRODUCT_STOCK_ERROR);
                    }

                    OrderItemUtil.create(orderItem,cartDTO,orderChild,productVO);
                    //替换为批量增加
                    //orderItemMapper.insert(orderItem);
                    orderItemList.add(orderItem);

                    shopProductPrice = shopProductPrice.add(orderItem.getTotalPrice());
                }
            }
            //设置商品总金额
            orderChild.setProductPrice(shopProductPrice);
            //批量增加订单详情
            orderItemMapper.insertMore(orderItemList);

            //获取所有有效满减活动  业务逻辑暂时设定为所有活动不可叠加 只取其一
            //List<ShopActivity> activityList = shopActivityService.findValidAllActity(1, 1, new Date());

            //获取满足满减活动 , 条件 生效金额最大 的活动
            ShopActivity maxActivity = shopActivityService.findMaxActivity(Integer.valueOf(String.valueOf(key)), MallEnum.ACTIVITY_REDUCE.getCode(), new Date(),totalPrice);

            if (null != maxActivity) {
                //加上 店铺活动的优惠金额
                shopDeratePrice = shopDeratePrice.add(maxActivity.getDeratePrice());
                //设置使用的店铺活动ID
                orderChild.setShopActivityId(SortUtil.strAppend("",String.valueOf(maxActivity.getId())));
            }

            //暂时定为每次只能用一个优惠券
            if (orderDTO.getShopActivityId() != null) {
                MemberCoupon memberCoupon = memberCouponService.findByShopIdAndMemberId(orderDTO.getMemberId(), orderDTO.getShopActivityId());
                if (null != memberCoupon) {
                    if (orderChild.getProductPrice().compareTo(memberCoupon.getOperationPrice()) >= 0) {
                        //加上优惠券优惠金额
                        shopDeratePrice = shopDeratePrice.add(memberCoupon.getDeratePrice());
                        if(null != orderChild.getShopActivityId()) {
                            //设置使用的店铺活动ID
                            orderChild.setShopActivityId(SortUtil.strAppend(orderChild.getShopActivityId(),String.valueOf(memberCoupon.getShopActivityId())));
                        }
                    }
                }
            }

            //店铺总运费
            BigDecimal shopPostagePrice = BigDecimal.ZERO;

            ShopProductFreightConfig config = freightConfigService.findByShopId(Integer.valueOf(String.valueOf(key)));

            //如果运费为0则直接设置为0,如果不为零则判断其他规则
            if (null == config || config.getFreight().compareTo(BigDecimal.ZERO) == 0) {
                orderChild.setPostagePrice(BigDecimal.ZERO);
            }else {

                //先判断消费是否达到减免运费标准 根据商品总价格判断
                if(config.getDerateFreight().compareTo(shopProductPrice) <= 0) {
                    orderChild.setPostagePrice(BigDecimal.ZERO);
                }else {
                    //如果没达到减免金额标准 则判断是否是加收运费的区域
                    if(config.getAddAreaCodes().contains(areaCode)) {
                        shopPostagePrice = shopPostagePrice.add(config.getFreight()).add(config.getAddFreight());
                    }else {
                        shopPostagePrice = shopPostagePrice.add(config.getFreight());
                    }
                    orderChild.setPostagePrice(shopPostagePrice);
                }
            }

            //设置店铺减免金额 =  满减活动减免金额 +  优惠券减免金额
            orderChild.setShopReducePrice(shopDeratePrice);

            //设置订单总金额 = 商品总金额 - 店铺减免总金额 + 运费
            shopTotalPrice = shopProductPrice.subtract(shopDeratePrice).add(shopPostagePrice);
            orderChild.setTotalPrice(shopTotalPrice);
            orderChild.setPayPrice(orderChild.getTotalPrice());
            //设置该笔订单积分
            orderChild.setOrderIntegral(DecimalUtil.integral(orderChild.getTotalPrice(),scale));
            //设置订单状态
            orderChild.setOrderStatus(OrderEnum.ORDER_STATUS_NOT_PAY.getCode().byteValue());
            orderChildMapper.insert(orderChild);

            integral = integral.add(orderChild.getPayPrice().divide(BigDecimal.valueOf(scale)));
            productTotalPrice = productTotalPrice.add(orderChild.getProductPrice());
            totalPrice = totalPrice.add(orderChild.getTotalPrice());
            orderShopDeratePrice = orderShopDeratePrice.add(orderChild.getShopReducePrice());
            orderPostagePrice = orderPostagePrice.add(shopPostagePrice);
        }

        //商城满减活动
        ShopActivity maxActivity = mallActivityService.findMaxActivity(MallEnum.ACTIVITY_REDUCE.getCode(), productTotalPrice);
        if (null != maxActivity) {
            //加上 店铺活动的优惠金额
            orderMallDeratePrice = orderMallDeratePrice.add(maxActivity.getDeratePrice());
            mallOrder.setMallActivityId(String.valueOf(maxActivity.getId()));
        }
        //用户使用的商城优惠券
        if(null != orderDTO.getMallActivityId()) {
            MemberCoupon mallCoupon = memberCouponService.findByMallIdAndMemberId(orderDTO.getMemberId(), orderDTO.getMallActivityId());
            if (null != mallCoupon) {
                if (productTotalPrice.compareTo(mallCoupon.getOperationPrice()) >= 0) {
                    //加上优惠券优惠金额
                    orderMallDeratePrice = orderMallDeratePrice.add(mallCoupon.getDeratePrice());
                    mallOrder.setMallActivityId(SortUtil.strAppend(mallOrder.getMallActivityId(),String.valueOf(mallCoupon.getMallActivityId())));
                }
            }
        }
        mallOrder.setProductPrice(productTotalPrice);
        mallOrder.setShopReducePrice(orderShopDeratePrice);
        mallOrder.setMallReducePrice(orderMallDeratePrice);

        //订单总金额 = 商品总金额  -商城减免总金额(满减 + 优惠券)
        totalPrice = productTotalPrice.subtract(orderMallDeratePrice);
        mallOrder.setTotalPrice(totalPrice);

        //实际支付价格精确到小数点后两位
        mallOrder.setPayPrice(totalPrice.setScale(2,BigDecimal.ROUND_HALF_UP));
        mallOrder.setPostagePrice(orderPostagePrice);
        mallOrder.setOrderIntegral(DecimalUtil.integral(mallOrder.getTotalPrice(),scale));

        //支付状态为待支付
        mallOrder.setOrderStatus(OrderEnum.ORDER_STATUS_NOT_PAY.getCode().byteValue());
        mallOrder.setPayStatus(OrderEnum.PAY_STATUS_WAIT.getCode().byteValue());

        if (null != orderDTO.getInvoiceId()) {
            //1普通发票
            mallOrder.setIsInvoice(OrderEnum.IS_INVOICE_DEFAULT.getCode().byteValue());
            mallOrder.setInvoiceId(orderDTO.getInvoiceId());
        }else {
            mallOrder.setIsInvoice(OrderEnum.IS_INVOICE_NO.getCode().byteValue());
        }

        //redis购物车删除已购买商品
        cartService.deleteChecked(cart, mallOrder.getMemberId());
        //支付后的逻辑  ----------------|||||

        //商品库存扣减
        //订单状态改变
        //用户积分增加
        //修改用户优惠券状态
        return mallOrderMapper.insert(mallOrder);

    }

    @Override
    @Transactional
    public int createOrder(OrderDTO orderDTO) {

        ProductVO product = productService.findProductBySkuId(orderDTO.getSkuId());

        if(null == product) {
            throw new OrderException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        if(product.getIsGrund().intValue() != ProductEnum.IS_GRUND_UP.getCode() ||
                product.getIsAudit().intValue() != ProductEnum.IS_AUDIT_YES.getCode() ) {
            throw new OrderException(ResultEnum.PRODUCT_NOT_GRUND);
        }
        if(product.getProductStock() <= 0 ) {
            throw new OrderException(ResultEnum.PRODUCT_STOCK_ERROR);
        }

        //订单主表
        MallOrder mallOrder = new MallOrder();

        //生成该店铺订单
        OrderChild orderChild = new OrderChild();

        //订单详情表
        OrderItem orderItem = new OrderItem();

        String areaCode = "";
        //收货地址
        if(null != orderDTO.getAddressId()) {
            MemberAddress address = memberAddressService.findByIdAndMemberId(orderDTO.getAddressId(),orderDTO.getMemberId());
            areaCode = address.getReceiverAddressCode();
            BeanUtils.copyProperties(address,mallOrder);
        }

        //发票
        if (orderDTO.getInvoiceId() != null) {
            mallOrder.setInvoiceId(orderDTO.getInvoiceId());
            mallOrder.setIsInvoice(OrderEnum.IS_INVOICE_DEFAULT.getCode().byteValue());
        }else {
            mallOrder.setIsInvoice(OrderEnum.IS_INVOICE_NO.getCode().byteValue());
        }

        orderChild.setId(IdWorker.getIdStr());
        orderChild.setMemberId(orderDTO.getMemberId());
        orderChild.setMallOrderSn(IdWorker.getIdStr());

        //该店铺商品总额
        BigDecimal shopProductPrice = product.getSellMobilePrice().multiply(BigDecimal.valueOf(orderDTO.getNums()));
        //商城满减总金额
        BigDecimal orderMallDeratePrice = BigDecimal.ZERO;

        orderItem.setId(IdWorker.getIdStr());
        orderItem.setMemberId(orderDTO.getMemberId());
        orderItem.setSkuProductId(orderDTO.getSkuId());
        orderItem.setQuantity(orderDTO.getNums());
        orderItem.setCurrentUnitPrice(product.getSellMobilePrice());
        orderItem.setOrderChildId(orderChild.getId());
        orderItem.setTotalPrice(shopProductPrice);
        orderItem.setProductName(product.getSkuName());

        orderItemMapper.insert(orderItem);

        //获取满足满减活动 , 条件 生效金额最大 的活动
        ShopActivity maxShopActivity = shopActivityService.findMaxActivity(Integer.valueOf(product.getShopId()),
                MallEnum.ACTIVITY_REDUCE.getCode(), new Date(),shopProductPrice);

        //该店铺优惠总额
        BigDecimal shopDeratePrice = BigDecimal.ZERO;

        if (null != maxShopActivity) {
            //加上 店铺活动的优惠金额
            shopDeratePrice = shopDeratePrice.add(maxShopActivity.getDeratePrice());
            //设置使用的店铺活动ID
            orderChild.setShopActivityId(SortUtil.strAppend("",String.valueOf(maxShopActivity.getId())));
        }

        //暂时定为每次只能用一个优惠券
        if (orderDTO.getShopActivityId() != null) {
            MemberCoupon memberCoupon = memberCouponService.findByShopIdAndMemberId(orderDTO.getMemberId(), orderDTO.getShopActivityId());
            if (null != memberCoupon) {
                if (shopProductPrice.compareTo(memberCoupon.getOperationPrice()) >= 0) {
                    //加上优惠券优惠金额
                    shopDeratePrice = shopDeratePrice.add(memberCoupon.getDeratePrice());
                    //设置使用的店铺活动ID
                    orderChild.setShopActivityId(SortUtil.strAppend(orderChild.getShopActivityId(),String.valueOf(memberCoupon.getShopActivityId())));
                }
            }
        }

        //店铺总运费
        BigDecimal shopPostagePrice = BigDecimal.ZERO;

        ShopProductFreightConfig config = freightConfigService.findByShopId(product.getShopId());

        if(null != config) {
            //如果运费为0则直接设置为0,如果不为零则判断其他规则
            if (config.getFreight().compareTo(BigDecimal.ZERO) == 0) {
                orderChild.setPostagePrice(BigDecimal.ZERO);
            }else {

                //先判断消费是否达到减免运费标准 根据商品总价格判断
                if(config.getDerateFreight().compareTo(shopProductPrice) <= 0) {
                    orderChild.setPostagePrice(BigDecimal.ZERO);
                }else {
                    //如果没达到减免金额标准 则判断是否是加收运费的区域
                    if(config.getAddAreaCodes().contains(areaCode)) {
                        shopPostagePrice = shopPostagePrice.add(config.getFreight()).add(config.getAddFreight());
                    }else {
                        shopPostagePrice = shopPostagePrice.add(config.getFreight());
                    }
                    orderChild.setPostagePrice(shopPostagePrice);
                }
            }
        }else {
            orderChild.setPostagePrice(BigDecimal.ZERO);
        }


        //商城满减活动
        ShopActivity maxMallActivity = mallActivityService.findMaxActivity(MallEnum.ACTIVITY_REDUCE.getCode(), shopProductPrice);
        if (null != maxMallActivity) {
            //加上 店铺活动的优惠金额
            orderMallDeratePrice = orderMallDeratePrice.add(maxMallActivity.getDeratePrice());
            mallOrder.setMallActivityId(String.valueOf(maxMallActivity.getId()));
        }
        //用户使用的商城优惠券
        if(null != orderDTO.getMallActivityId()) {
            MemberCoupon mallCoupon = memberCouponService.findByMallIdAndMemberId(orderDTO.getMemberId(), orderDTO.getMallActivityId());
            if (null != mallCoupon) {
                if (shopProductPrice.compareTo(mallCoupon.getOperationPrice()) >= 0) {
                    //加上优惠券优惠金额
                    orderMallDeratePrice = orderMallDeratePrice.add(mallCoupon.getDeratePrice());
                    //设值使用的商城活动
                    mallOrder.setMallActivityId(SortUtil.strAppend(mallOrder.getMallActivityId(),String.valueOf(mallCoupon.getMallActivityId())));
                }
            }
        }

        //设置商品总金额
        orderChild.setProductPrice(shopProductPrice);
        //设置店铺减免金额 =  满减活动减免金额 +  优惠券减免金额
        orderChild.setShopReducePrice(shopDeratePrice);

        //设置订单总金额 = 商品总金额 - 店铺减免总金额 + 运费
        orderChild.setTotalPrice(shopProductPrice.subtract(shopDeratePrice).add(shopPostagePrice));
        orderChild.setPayPrice(orderChild.getTotalPrice());
        //设置该笔订单积分
        orderChild.setOrderIntegral(DecimalUtil.integral(orderChild.getTotalPrice(),scale));
        //设置订单状态
        orderChild.setOrderStatus(OrderEnum.ORDER_STATUS_NOT_PAY.getCode().byteValue());
        orderChildMapper.insert(orderChild);
        //该笔订单总金额 = 店铺商品总金额 - 商城减免总金额 (前面已经减过运费)
        BigDecimal totalPrice = orderChild.getTotalPrice().subtract(orderMallDeratePrice);

        BeanUtils.copyProperties(orderChild,mallOrder);

        mallOrder.setId(IdWorker.getIdStr());
        mallOrder.setMallReducePrice(orderMallDeratePrice);
        mallOrder.setTotalPrice(totalPrice);
        mallOrder.setPayPrice(totalPrice.setScale(2,BigDecimal.ROUND_HALF_UP));
        mallOrder.setOrderSn(orderChild.getMallOrderSn());
        mallOrder.setPayStatus(OrderEnum.PAY_STATUS_WAIT.getCode().byteValue());


        //支付后的逻辑


        //商品库存扣减
//        productService.reduceStock();
        //订单状态改变
        //用户积分增加
        //修改用户优惠券状态

        return mallOrderMapper.insert(mallOrder);
    }

    @Override
    public List<MallOrder> findWaitPayOrder(MallOrder order) {
        List<MallOrder> query = this.findByQuery(order);
        for (MallOrder mallOrder: query) {
            List<OrderItem> orderItems = orderItemMapper.findByOrderChildId(mallOrder.getOrderSn(), mallOrder.getMemberId());
            mallOrder.setOrderItemList(orderItems);
        }
        return query;
    }
}
